package com.ebrothers.isns;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ebrothers.isns.common.JsonConverter;
import com.ebrothers.isns.common.Params;
import com.ebrothers.isns.common.Utils;
import com.ebrothers.isns.dao.DAOException;
import com.ebrothers.isns.dao.QuestionDAO;
import com.ebrothers.isns.vo.Question;
import com.ebrothers.isns.vo.ResultVo;

/**
 * Servlet implementation class NewQuestion
 */
public class NewQuestion extends HttpServlet {
	private static final Logger logger = Logger.getLogger(NewQuestion.class);
	private static final long serialVersionUID = 1L;

	private QuestionDAO questionDAO;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewQuestion() {
		super();
		questionDAO = new QuestionDAO();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String uName = request.getParameter(Params.U_NAME);
		String qBody = request.getParameter(Params.Q_BODY);
		String qType = request.getParameter(Params.Q_TYPE);
		String qPos = request.getParameter(Params.Q_POS);
		logger.info("[NewQuestions] uName=" + uName + ", qBody=" + qBody
				+ ", qType=" + qType + ", qPos=" + qPos);
		long result = -1;
		if (uName != null && qBody != null) {
			Question q = new Question();
			q.setBody(qBody);
			q.getOwner().setName(uName);
			try {
				q.setType(Integer.parseInt(qType));
			} catch (NumberFormatException e) {
				q.setType(-1);
			}
			q.setTriggerLocation(Utils.stringToLocation(qPos));
			try {
				result = questionDAO.insertQuestion(q);
			} catch (DAOException e) {
				logger.error("GOT AN ERROR!", e);
				throw new ServletException(e);
			}
		}
		ResultVo resultVo = new ResultVo();
		resultVo.setResult(String.valueOf(result));
		String json = JsonConverter.beanToJson(resultVo);
		PrintWriter out = response.getWriter();
		logger.info("[NewQuestions] result=" + json);
		out.write(json);
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
